<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
    <div class="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
        <div class="max-w-4xl mx-auto bg-white shadow-xl rounded-lg overflow-hidden">
            <header class="bg-blue-600 py-6">
                <h1 class="text-3xl font-bold text-center text-white">JBoltAI血常规报告智能分析系统</h1>
            </header>
            <main class="p-6 space-y-6">
                <!-- 文件上传区域 -->
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
                    <input type="file" id="file-upload" class="hidden" @change="handleFileUpload"
                           accept=".jpg,.png"/>
                    <label for="file-upload" class="cursor-pointer">
                        <div class="text-gray-600">
                            <i class="fas fa-cloud-upload-alt text-4xl mb-3"></i>
                            <p class="text-lg">点击上传血常规报告图片</p>
                            <p class="text-sm text-gray-500 mt-2">支持 JPG、PNG格式</p>
                        </div>
                    </label>
                    <button @click="triggerFileUpload"
                            class="mt-4 bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded !rounded-button whitespace-nowrap">
                        选择文件
                    </button>
                </div>
                <!-- 上传状态提示 -->
                <div v-if="uploadStatus"
                     :class="['text-center py-2 rounded', (uploadStatus === '上传成功' || uploadStatus === '分析完成') ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700']">
                    {{ uploadStatus }}
                </div>
                <!-- AI分析中提示 -->
                <div v-if="isAnalyzing"
                     class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white p-6 rounded-lg shadow-xl text-center">
                        <i class="fas fa-spinner fa-spin text-4xl text-blue-500 mb-4"></i>
                        <p class="text-xl font-semibold">AI智能分析中...</p>
                    </div>
                </div>
                <!-- 分析结果表格 -->
                <div v-if="analysisResults.length > 0" class="overflow-x-auto">
                    <table class="min-w-full bg-white">
                        <thead class="bg-gray-100">
                        <tr>
                            <th class="py-3 px-4 text-left">检测项目</th>
                            <th class="py-3 px-4 text-left">检测结果</th>
                            <th class="py-3 px-4 text-left">参考范围</th>
                            <th class="py-3 px-4 text-left">单位</th>
                            <th class="py-3 px-4 text-left">结果分析</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="(item, index) in analysisResults" :key="index"
                            :class="index % 2 === 0 ? 'bg-gray-50' : 'bg-white'">
                            <td class="py-2 px-4">{{ item.name }}</td>
                            <td class="py-2 px-4" :class="getResultClass(item.pass)">{{ item.result }}</td>
                            <td class="py-2 px-4">{{ item.min }} ~ {{item.max}}</td>
                            <td class="py-2 px-4">{{ item.unit }}</td>
                            <td class="py-2 px-4" :class="getResultClass(item.pass)">{{ item.pass?'正常':'异常' }}</td>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <!-- 总体分析报告 -->
                <div v-if="overallAnalysis" class="bg-gray-50 p-4 rounded-lg">
                    <h2 class="text-xl font-semibold mb-2">总体分析报告</h2>
                    <p class="text-gray-700">{{ overallAnalysis }}</p>
                    <!-- 细分模块分析 -->
                    <div class="mt-4 space-y-4">
                        <div v-for="(analysis, index) in detailedAnalysis" :key="index"
                             class="bg-white p-3 rounded-md shadow-sm">
                            <h3 class="text-lg font-medium mb-2">{{ analysis.name }}</h3>
                            <p class="text-gray-600">{{ analysis.content }}</p>
                        </div>
                    </div>
                </div>
                <!-- 操作按钮区 -->
                <div class="flex justify-center space-x-4">
<!--                    <button @click="resetUpload"-->
<!--                            class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded !rounded-button whitespace-nowrap">-->
<!--                        重新上传-->
<!--                    </button>-->
                    <button @click="submitCase"
                            class="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded !rounded-button whitespace-nowrap">
                        案例数据
                    </button>
                    <button @click="printReport"
                            class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded !rounded-button whitespace-nowrap">
                        打印报告
                    </button>
                </div>
            </main>
            <footer class="bg-gray-100 py-4 text-center text-gray-600 text-sm">
            </footer>
        </div>
    </div>
</template>
<script lang="ts" setup>
import {ref, computed, onMounted, watch} from 'vue';
//----------- demo代码
import {
    JBoltApi
} from "@/service/request/index.js";
import {
    useWebSocketStore
} from "@/stores/websocket.js";
import AiChat from '@/components/_builtin/jb-ai-chat/index.js'
import {storeToRefs} from "pinia";
const chatInstance = ref(null);
const webSocketStore = storeToRefs(useWebSocketStore())
watch(() => webSocketStore.ws.value, () => {
    console.debug("websock重连")
    if (chatInstance.value) {
        chatInstance.value.updateWebSocket(webSocketStore.ws.value)
    }
})
const session = ref(null);
//1. 到.env配置文件中，配置该demo的appId
//2. 进入页面的时候，创建一个会话
function addSession() {
    JBoltApi.post('/aiAppSession/add', {
        name: '新的Demo会话',
        appId: import.meta.env.VITE_APP_ID,
    }).then((res) => {
        session.value = res.result.data;

        initWebsocket();
    });
}
onMounted(() => {
    addSession();
})

//3. 初始化websocket
function initWebsocket() {
    chatInstance.value = new AiChat(null, {
        // websocketUrl: 'ws://192.168.31.118:8013/ws',
        websocketInstance: webSocketStore.ws.value,
        app: import.meta.env.VITE_APP_ID,
        sessionId: session.value.id,
        global: null,
        onMsgSend: (msg ) => {

        },
        onMsgReceive: (msg) => {
            switch (msg.action) {
                case "response":
                    let res = JSON.parse(msg.data.content.text);
                    console.debug("接收到：", res);
                    res.list.forEach((item) => {
                        item.pass = item.result >= item.min && item.result <= item.max;
                    });
                    analysisResults.value = res.list;
                    detailedAnalysis.value =res.detailedAnalysis;
                    overallAnalysis.value = res.summary;
                    uploadStatus.value = '分析完成';
                    break;
                case "over":
                    isAnalyzing.value = false;
                    break;
                case "error":
                    alert(msg.data.msg);
                    break;
            }
        },
    })
}

const submit = (url) => {
    // 模拟自动选择内置案例文件并开始分析
    isAnalyzing.value = true;

    chatInstance.value.sendMessage({
        action: 'request',
        data: {
            role: 'user',
            content: { "text": '' },
            file: url
            // files: files
        }
    })
}


const submitCase = () => {

    submit("https://assets.d2danao.com/tmp/435.jpg")
    return;
};


//----------- demo代码


const uploadStatus = ref('');
const analysisResults = ref([]);
const overallAnalysis = ref('');
const isAnalyzing = ref(false);
const detailedAnalysis = ref([]);
const handleFileUpload = (event: Event) => {
    const file = (event.target as HTMLInputElement).files?.[0];
    if (file) {
        resetUpload();
        uploadStatus.value = '正在上传...';
        JBoltApi.uploadToQiniu(file, "/ndemo/report_helper/{date(yyyyMMddHHmm)}/{random(6)}.{oriSuffix}", '', null, (res) => {
            console.debug("上传成功：", res)
            uploadStatus.value = '上传成功';
            submit(res.url)
        } )
        return;

    }
};
const triggerFileUpload = () => {
    const fileInput = document.getElementById('file-upload') as HTMLInputElement;
    fileInput.click();
};
const resetUpload = () => {
    uploadStatus.value = '';
    analysisResults.value = [];
    overallAnalysis.value = '';
    const fileInput = document.getElementById('file-upload') as HTMLInputElement;
    fileInput.value = '';
};
const printReport = () => {
    window.print();
};

const getResultClass = computed(() => (status: boolean) => {
    return status ? 'text-green-600' : 'text-red-600';
});
</script>
<style scoped>
@media print {
    body * {
        visibility: hidden;
    }

    .max-w-4xl, .max-w-4xl * {
        visibility: visible;
    }

    .max-w-4xl {
        position: absolute;
        left: 0;
        top: 0;
    }
}
</style>
